var userId = null === getParameter("userId") ? -1 : getParameter("userId");

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'tradeinfo/list',
        datatype: "json",
        colModel: [
			{ label: 'ID', name: 'id', width: 0, key: true, hidden:true},
			{ label: '付款方', name: 'phone', sortable:false, width: 60 },
			{ label: '收款方', name: 'recPhone', sortable:false, width: 60 },
			{ label: '订单号', name: 'orderNo', sortable:false, width: 68 },
            { label: '币种', name: 'ytfType', sortable:false, width: 38, formatter: function(value, options, row){
            	var val = "";
				if(value == 0){
					val = "IMU";
				}else if(value == 1){
					val = "以太坊";
				}else if(value == 2){
                    val = "易买宝";
                }else if(value == 3){
                    val = "KTC";
                }else if(value == 4){
                    val = "GET";
                }else if(value == 5){
                    val = "贝壳";
                }else if(value == 6){
                    val = "HBC";
                }else if(value == 7){
                    val = "BTC";
                }else if(value == 8){
                    val = "FCG";
                }
            	return val;
            }},
			{ label: '类型', name: 'orderType',align : 'center', sortable:false, width: 36 ,formatter: function(value, options, row)
				{
	                if (value == 0){
	                    return '<span class="label label-primary">转出</span>';
	                }else if(value == 1){
	                	return '<span class="label label-default">兑换</span>';
	                }else if(value == 2){
	                	return '<span class="label label-warning">转入</span>';
	                }else if(value == 3){
	                	return '<span class="label label-info">储存</span>';
	                }else if(value == 4){
	                	return '<span class="label label-danger">提取</span>';
	                }else if(value == 5){
                        return '<span class="label label-success">私募</span>';
                    }else if(value == 20){
                        return '<span class="label label-info">撤销</span>';
                    }else {
	                	return '';
					}
				}
			},
            { label: '交易前', name: 'smoney', sortable:false, width: 40 },
            { label: '交易数', name: 'money', sortable:false, width: 40 },
            { label: '交易费', name: 'fee', sortable:false, width: 40 },
            { label: '交易后', name: 'emoney', sortable:false, width: 40 },
	        { label: '状态', name: 'orderState', width: 36, formatter: function(value, options, row){
				return value === 0 ? 
					'<span class="label label-warning">处理中</span>' : 
					'<span class="label label-success">成功</span>';
	        }},
            { label: '交易时间', name: 'orderCreate', sortable:false, width: 68 },
            { label: '交易ID', name: 'transId', sortable:false, width: 80 },
            { label: '备注', name: 'detail', sortable:false, width: 38 }
			/*
			{ label: '接受地址', name: 'recAddr', sortable:false, width: 150 }*/
        ],
		viewrecords: true,
        height: 385,
        rowNum: 20,
		rowList : [10,20,30,50,100,200],
        rownumbers: false, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.pageNum",
            total: "page.pages",
            records: "page.total"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    jQuery("#jqGrid").jqGrid('navGrid','#jqGrid',{edit:false,add:false,del:false});
    
    //过滤时间
    var rangetime = $('#filterTime').daterangepicker({
        autoApply:false,
        singleDatePicker:false,
        showDropdowns:true,         // 是否显示年月选择条件
    	timePicker: true, 			// 是否显示小时和分钟选择条件
    	timePickerIncrement: 10, 	// 时间的增量，单位为分钟
        timePicker24Hour : true,
        opens : 'left', //日期选择框的弹出位置
        startDate: moment().startOf('year'), //startDate和endDate 的值如果跟 ranges 的两个相同则自动选择ranges中的行. 这里选中了清空行
        endDate: moment().endOf('year'),
    	ranges: {
    		'今日': [moment().startOf('day'), moment().endOf('day')],
    		'昨日': [moment().subtract(1, 'days').startOf('day'), moment().subtract(1, 'days').endOf('day')],
    		'最近7日': [moment().subtract(6, 'days'), moment()],
    		'最近30日': [moment().subtract(29, 'days'), moment()],
    		'本月': [moment().startOf('month'), moment().endOf('month')],
    		'上个月': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
    		'本年': [moment().startOf('year'), moment().endOf('year')],
    		'去年': [moment().subtract(1, 'year').startOf('year'), moment().subtract(1, 'year').endOf('year')]
    	},
        locale : {
            //format: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm',
            separator : ' - ',
        	customRangeLabel : '自定义',
            applyLabel : '确定',
            cancelLabel : '取消',
            fromLabel : '起始时间',
            toLabel : '结束时间',
            daysOfWeek : [ '日', '一', '二', '三', '四', '五', '六' ],
            monthNames : [ '一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月' ],
            firstDay : 1,
            startDate: moment().startOf('day'),
            endDate: moment().endOf('day')
        }
    },
    function(start, end, label) // 格式化日期显示框
    {
    	//选择时间 回调，暂时不做操作。。。
        $('#filterTime').val(start.format('YYYY-MM-DD HH:mm') + " - " + end.format('YYYY-MM-DD HH:mm'));
    });
    
    //setTimeout("$('#filterTime').val('')", 100);
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			key: null
		},
		showList: true,
		title: null,
		dto: {}
	},
	methods: {
		query: function () {
			
			vm.reload();
		},
        exportData: function () {
            vm.showList = true;
            var _postData = $("#jqGrid").jqGrid('getGridParam','postData');
            delete _postData['sts'];
            delete _postData['ets'];
            _postData['p'] = $("#payPhone").val();
            _postData['ytfType'] = $("#ytfType").val();
            _postData['recPhone'] = $("#recPhone").val();
            _postData['equalsf'] = $("#equalsf").val();
            _postData['money'] = $("#money").val();
            if((vtime = $.trim($('#filterTime').val())) != '')
            {
                if(vtime.indexOf(" - ") > -1)
                {
                    _postData['sts'] = ($.trim(vtime.split(" - ")[0]) + ":00");
                    _postData['ets'] = ($.trim(vtime.split(" - ")[1]) + ":59");
                }
                else
                {
                    _postData['sts'] = getTime(vtime);
                }
            };
            console.debug(_postData);
            $.ajax({
                type: "GET",
                url: baseURL + "tradeinfo/export",

                data: _postData,
                success: function(r){
                    if(r.code === 0){
                        alert('导出成功', function(index){
                            $("#jqGrid").trigger("reloadGrid");
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
		trash: function () {
			$('#filterTime').val('');
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.dto = {};
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
		saveOrUpdate: function (event) {
			var url = vm.dto.id == null ? baseURL + "tradeinfo/save" : baseURL + "tradeinfo/update";
			console.log(JSON.stringify(vm.dto));
			$.ajax({
				type: "POST",
			    url: url,
			    data: JSON.stringify(vm.dto),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		delCol: function (id) {
			if(id == null){
				return ;
			}
			var ids = [id];
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "tradeinfo/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "PUT",
				    url: baseURL + "tradeinfo/delete",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code === 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "tradeinfo/info/"+id, function(r){
                vm.dto = r.dto;
            });
		},
		reload: function (event) {
			vm.showList = true;
			var _postData = $("#jqGrid").jqGrid('getGridParam','postData');
			delete _postData['sts'];
			delete _postData['ets'];
			_postData['p'] = $("#payPhone").val();
			_postData['ytfType'] = $("#ytfType").val();
			_postData['recPhone'] = $("#recPhone").val();
            _postData['equalsf'] = $("#equalsf").val();
            _postData['money'] = $("#money").val();
			if((vtime = $.trim($('#filterTime').val())) != '')
			{
				if(vtime.indexOf(" - ") > -1)
				{
					_postData['sts'] = ($.trim(vtime.split(" - ")[0]) + ":00");
					_postData['ets'] = ($.trim(vtime.split(" - ")[1]) + ":59");
				}
				else
				{
					_postData['sts'] = getTime(vtime);
				}
			}

			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                page:page
            }).trigger("reloadGrid");
		},
		vexport: function (event) {
			var params = "?token=" + token;
			if(null != $("#payPhone").val()){
				params += "&p=" + $("#payPhone").val();
			}
			if(null != $("#ytfType").val()){
				params += "&ytfType=" + $("#ytfType").val();
			}
			if(null != $("#recPhone").val()){
				params += "&recPhone=" + $("#recPhone").val();
			}
			if(null != $("#equalsf").val()){
				params += "&equalsf=" + $("#equalsf").val();
			}
			if(null != $("#money").val()){
				params += "&money=" + $("#money").val();
			}
			
			var vtime;
			if((vtime = $.trim($('#filterTime').val())) != '')
			{
				if(vtime.indexOf(" - ") > -1)
				{
					params += "&sts=" + ($.trim(vtime.split(" - ")[0]) + ":00");
					params += "&ets=" + ($.trim(vtime.split(" - ")[1]) + ":59");
				}
				else
				{
					params += "&sts=" + ($.trim(vtime) + ":00");
				}
			}
			
			location.href = baseURL + "tradeinfo/exprot" + params;
		} 
	}
});